
#import "YQPShopVC.h"
#import "YQNavTitleView.h"
#import "YQSearchBaseBar.h"
#import "MYShopSearchVC.h"
#import "YQPShopCatalogModel.h"
#define categoryCollViewItemSizeW (88 / 375.0) * kYQPScreenWidth
#define categoryCollViewItemSizeH (47 / 88.0) * categoryCollViewItemSizeW

@interface YQPShopVC ()<YQSearchBaseBarDelegate,UITableViewDelegate,UITableViewDataSource,MYShopGoodsCellDelegate>
@property (nonatomic, strong) YQSearchBaseBar * searchBar;
@property (nonatomic, strong) YQBaseTableView * categoryTableView;
@property (nonatomic, strong) YQBaseTableView * goodsTableView;

@property (nonatomic, assign) BOOL isRepeatRolling;

/// 一级分类数组
//@property (strong, nonatomic) NSMutableArray *categoryArray;
//一级model
//@property (strong, nonatomic) YQPGoodCategoryOneModel *model;
/// 二级分类数组
@property (strong, nonatomic) NSMutableArray *catalogArray;
//二级model
//@property (strong, nonatomic) YQPCatalogModel *catalogModel;

@property (nonatomic, strong) NSMutableArray * indexArr;

@end

@implementation YQPShopVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isRepeatRolling = NO; // 默认NO

    self.goodsTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getCategoryDataList)];
}

#pragma mark -分类名称数组
- (void)getCategoryDataList
{
    YQSHOWLOADINGINVIEW
    [YQPNetWorkingManager sendPostRequest:@"/api/search/all/catalog/list" parameters:nil success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        YQHIDELOADINGTIPS
        [self.goodsTableView.mj_header endRefreshing];
        [self.dataArr removeAllObjects];
        [self.indexArr removeAllObjects];
        [self.catalogArray removeAllObjects];
         NSArray *arr = [YQPShopCatalogModel mj_objectArrayWithKeyValuesArray:responseObject.data];
        
//        arr = [arr qmui_filterWithBlock:^BOOL(YQPShopCatalogModel *item) {
//            return item.catalog2List.count > 0;
//        }];
        NSInteger totalCatalog2Sum = 0;
        for (NSInteger i = 0; i < arr.count; i++) {
            YQPShopCatalogModel *catalogModel = arr[i];
            [self.indexArr addObject:[NSString stringWithFormat:@"%zd",totalCatalog2Sum]];
            totalCatalog2Sum += catalogModel.catalog2List.count;
            for (YQPShopCatalog2Model *catalog2Model in catalogModel.catalog2List) {
                [self.catalogArray addObject:catalog2Model];
            }
        }
        
        [self.dataArr addObjectsFromArray:arr];
        [self.categoryTableView reloadData];
        [self.goodsTableView reloadData];
        if (self.dataArr.count > 0) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
            [self.categoryTableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];

        }

     } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
         [self.goodsTableView.mj_header endRefreshing];
         YQHIDELOADINGTIPS
         YQUITIPSERROR(error);
     }];
}

-(void)setupView {
    [super setupView];
    YQNavTitleView *navView = [YQNavTitleView new];
    navView.frame = CGRectMake(0, 0, kScreenWidth, 44);
    navView.intrinsicContentSize = CGSizeMake(kScreenWidth, 44);
    self.navigationItem.titleView = navView;
    
    UIView *bgView = [UIView new];
    bgView.backgroundColor = UIColor.whiteColor;
    [navView addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(kScreenWidth, 44));
    }];
    
    [bgView addSubview:self.searchBar];
    [self.view addSubview:self.categoryTableView];
    [self.view addSubview:self.goodsTableView];
    
    [self.categoryTableView reloadData];
    
    [self getCategoryDataList];
    
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    //防止最后区间的时候，两个头部重合
    
    self.goodsTableView.contentInset = UIEdgeInsetsMake(0, 0, self.categoryTableView.height - (330 + 65), 0);
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.categoryTableView == tableView) {
        return self.dataArr.count;
    }else{
        return self.catalogArray.count;
    }
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if (self.categoryTableView == tableView) {
        YQPGoodCategoryOneModel *model = self.dataArr[indexPath.section];
        MYShopCategoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYShopCategoryTableViewCell"];
        cell.titleLb.text = model.name;
        return cell;
    }else{
        YQPShopCatalog2Model *model = self.catalogArray[indexPath.section];

        MYShopGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYShopGoodsCell"];
        cell.contentView.backgroundColor = HexColor(0xF6F6F6);
        cell.backgroundColor = HexColor(0xF6F6F6);
        cell.selectIndexPath = indexPath;
        cell.delegate = self;
//        [cell setModel:model];
        cell.goodsArray = model.catalog3List;
        return cell;
    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.categoryTableView == tableView) {
            return categoryCollViewItemSizeH;
    }else{
        YQPCatalogModel *model = self.catalogArray[indexPath.section];
        CGFloat collH = (model.catalog3List.count/3 + (model.catalog3List.count%3 == 0?0:1)) * 120;
            return collH;
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.categoryTableView == tableView) {
        
        if (self.categoryTableView == tableView) {
            NSIndexPath *tempIndexPath = indexPath;
            if (indexPath.section >0) {
                NSInteger sumSection = 0;
                for (NSInteger i = 0; i < indexPath.section; i++) {
                    YQPShopCatalogModel *catalogModel = self.dataArr[i];
                    sumSection += catalogModel.catalog2List.count;
                }
                tempIndexPath = [NSIndexPath indexPathForRow:0 inSection:sumSection];
            }
            
            self.isRepeatRolling = YES;
            //滚动到其相应的位置
            [self.goodsTableView scrollToRowAtIndexPath:tempIndexPath
                                       atScrollPosition:UITableViewScrollPositionTop animated:YES];
//            [self getCategoryTwoListApi:model];

        }else{
            
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (self.categoryTableView == tableView) {
        return 2;
    }
    return 0.001;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (self.goodsTableView == tableView) {

        MYShopCategoryHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MYShopCategoryHeader"];

    YQPCatalogEntityModel *catalogModel = self.catalogArray[section];
    header.titleLb.text = [NSString stringWithFormat:@"%@",catalogModel.name];
           
        return header;
    }else{
        return nil;
    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (self.goodsTableView == tableView) {
        return 56;
    }else{
        return 0.001;
    }
    
}
#pragma mark - UITableViewDelegate, UITableViewDataSource end
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.goodsTableView) {
        //取出当前显示的最顶部的cell的indexpath
        //当前tableview页面可见的分区属性 indexPathsForVisibleRows
        // 取出显示在 视图 且最靠上 的 cell 的 indexPath
        // 判断tableView是否滑动到最底部
        CGFloat height = scrollView.frame.size.height;
        CGFloat contentOffsetY = scrollView.contentOffset.y;
        CGFloat bottomOffset = scrollView.contentSize.height - contentOffsetY;
        if (bottomOffset <= height) {
            NSIndexPath *bottomIndexPath = [[self.goodsTableView indexPathsForVisibleRows] lastObject];
            
            NSInteger index = bottomIndexPath.section;
            NSInteger section = 0;
            if (!bottomIndexPath || index > self.catalogArray.count) {
                return;
            }
            for (NSInteger i = 0; i < self.indexArr.count; i++) {
                NSInteger num = [self.indexArr[i] integerValue];
                if (i == self.indexArr.count-1) {
                    if (index >= num) {
                        section = self.indexArr.count-1;
                    }
                }else{
                    NSInteger nextNum = [self.indexArr[i+1] integerValue];
                    if (num <= index && nextNum > index) {
                        section = i;
                    }
                }

            }
            if (self.isRepeatRolling == NO) { // 防止重复滚动
                [self.categoryTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:section] animated:NO scrollPosition:UITableViewScrollPositionNone];
            }
        } else {
            NSIndexPath *topIndexPath = [[self.goodsTableView indexPathsForVisibleRows] firstObject];
            NSInteger index = topIndexPath.section;
            NSInteger section = 0;
            
            if (!topIndexPath || index > self.catalogArray.count) {
                return;
            }
            
            for (NSInteger i = 0; i < self.indexArr.count; i++) {
                NSInteger num = [self.indexArr[i] integerValue];
                if (i == self.indexArr.count-1) {
                    if (index >= num) {
                        section = self.indexArr.count-1;
                    }
                }else{
                    NSInteger nextNum = [self.indexArr[i+1] integerValue];
                    if (num <= index && nextNum > index) {
                        section = i;
                    }
                }

            }
            
            if (self.isRepeatRolling == NO ) { // 防止重复滚动
                [self.categoryTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:section] animated:NO scrollPosition:UITableViewScrollPositionNone];
                //UITableViewScrollPositionMiddle
            }
        }
    }
}
// scrollView 开始拖动
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.isRepeatRolling = NO;
}
    
#pragma makr -- lazy
-(NSMutableArray *)indexArr {
    if (!_indexArr) {
        _indexArr = [NSMutableArray array];
    }
    return _indexArr;
}
-(NSMutableArray *)catalogArray {
    if (!_catalogArray) {
        _catalogArray = [NSMutableArray array];
    }
    return _catalogArray;
}

-(YQSearchBaseBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[YQSearchBaseBar alloc] initWithFrame:CGRectMake(12, 0, SCREEN_WIDTH - 24, 28)];
        _searchBar.top = 12;
        _searchBar.delegate = self;
        _searchBar.placeholderStr = kYQLS(@"搜索您要的物品");
    }
    return _searchBar;
}

-(YQBaseTableView *)categoryTableView {
    if (!_categoryTableView) {
        _categoryTableView = [[YQBaseTableView alloc] initWithFrame:CGRectMake(0, 0, categoryCollViewItemSizeW, kYQPScreenHeight - Height_TabBar - Height_NavBar - kHeight_Botton_SafeArea) style:(UITableViewStyleGrouped)];
        _categoryTableView.backgroundColor = HexColor(0xF6F6F6);
        _categoryTableView.delegate = self;
        _categoryTableView.dataSource = self;
        [_categoryTableView registerNib:[UINib nibWithNibName:@"MYShopCategoryTableViewCell" bundle:nil] forCellReuseIdentifier:@"MYShopCategoryTableViewCell"];
    }
    return _categoryTableView;
}

-(YQBaseTableView *)goodsTableView {
    if (!_goodsTableView) {
        _goodsTableView = [[YQBaseTableView alloc] initWithFrame:CGRectMake(categoryCollViewItemSizeW, 0, kYQPScreenWidth-categoryCollViewItemSizeW, kYQPScreenHeight - Height_TabBar - Height_NavBar - kHeight_Botton_SafeArea) style:(UITableViewStylePlain)];
        _goodsTableView.backgroundColor = HexColor(0xF6F6F6);
        _goodsTableView.delegate = self;
        _goodsTableView.dataSource = self;
        [_goodsTableView registerNib:[UINib nibWithNibName:@"MYShopCategoryHeader" bundle:nil] forHeaderFooterViewReuseIdentifier:@"MYShopCategoryHeader"];
        [_goodsTableView registerClass:[MYShopGoodsCell class] forCellReuseIdentifier:@"MYShopGoodsCell"];
    }
    return _goodsTableView;
}

#pragma makr -- lazy end
#pragma makr -- <YQSearchBaseBarDelegate>
- (BOOL)yq_searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    MYShopSearchVC *searchVC = [[MYShopSearchVC alloc] init];
    
    kYQPUSH(searchVC);
    return NO;
}
#pragma makr -- <YQSearchBaseBarDelegate> end
#pragma makr -- <MYShopGoodsCellDelegate>
-(void)didSelectItemAtImageAction:(NSIndexPath *)indexPath :(NSInteger)item {
    
    YQPShopCatalog2Model *model = self.catalogArray[indexPath.section];
    
    YQPShopCatalog3Model *catalog3Model = model.catalog3List[item];
    
    MYShopSearchVC *topicVC = [[MYShopSearchVC alloc] init];
    topicVC.selectID = catalog3Model.ID;
    kYQPUSH(topicVC);
}
@end
